import React from 'react';
import { NavLink, Link } from 'react-router-dom';
import md5 from 'md5';
import { Form, Input, Button, Checkbox, Popover } from 'antd';
import { getTeaRegValidCode, getEmailValidCode, getCountryList, teacherRegistry } from '../api';
import { formatDate, t_alert } from 'libs/utils';
import http from 'libs/http'

const FormItem = Form.Item;

const content = (
  <div>
    <p>Your Password Must</p>
    <p>･contain only alphanumeric characters</p>
    <p>･be between 6-30 characters</p>
    <p>･contain both letters and numbers </p>
  </div>
);

class TeacherRegistry extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      validCodeImg: '',
      emailValidCodeFlag: true,
      seconds: 'Get code',
      agreement: false,
      countryList: [],
    };
  }

  componentDidMount() {
    this.getTeaRegValidCode();
    // this.getCountryList();
  }

  getTeaRegValidCode = () => {
    getTeaRegValidCode((res) => {
      this.setState({
        validCodeImg: res.data,
      });
    });
  }

  getCountryList = () => {
    getCountryList((res) => {
      this.setState({
        countryList: res.data,
      });
    });
  }

  validateEmail = (rule, value, callback) => {
    const seconds = this.state.seconds;
    if (!value) {
      this.setState({
        emailValidCodeFlag: true,
      });
    } else if (!/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(value)) {
      this.setState({
        emailValidCodeFlag: true,
      });
      callback('Email format incorrect!');
    } else {
      http.get('/teacher/common/validEmail', {email: value})
      .then(res => {
        if(res.data) {
          this.setState({
            emailValidCodeFlag: true,
          });
          callback(<div>Account registered ? <Link to="/teacher/login_pad">Login now</Link></div>)
        }else {
          this.setState({
            emailValidCodeFlag: typeof seconds !== 'string',
          });
          callback();
        }
      })
    }
  }

  getEmailValidCode = () => {
    const form = this.props.form;
    const email = form.getFieldValue('email');
    let timer = null;
    this.setState({
      seconds: 120,
      emailValidCodeFlag: true,
    }, () => {
      getEmailValidCode({ email }, () => {
        timer = setInterval(() => {
          if (this.state.seconds === 0) {
            this.setState({
              seconds: 'Again',
              emailValidCodeFlag: false,
            });
            clearInterval(timer);
            timer = null;
            return;
          }
          this.setState(prevState => ({ seconds: prevState.seconds - 1 }));
        }, 1000);
      }, (data) => {
        t_alert(data.msg);
        setTimeout(() => {
          this.setState({
            seconds: 'Again',
            emailValidCodeFlag: false,
          });
        }, 1000);
      });
    });
  }

  agreeTerms = (e) => {
    this.setState({
      agreement: e.target.checked,
    });
  }

  // 注册
  handleSubmit = (e) => {
    e.preventDefault();
    if (!this.state.agreement) {
      t_alert('Read Teacher Policy First!');
      return;
    }
    const form = this.props.form;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { password: _password, ...rest } = values;
        teacherRegistry({
          password: md5(_password),
          ...rest
        }, () => {
          this.props.history.push('/teacher/gerenxinxi');
          form.resetFields();
        }, this.getTeaRegValidCode);
      }
    });
  }

  render() {
    const {
      validCodeImg, emailValidCodeFlag, seconds, countryList,
    } = this.state;
    const { getFieldDecorator } = this.props.form;

    return (
      <div className="teacher-registry">
        <div className="registry-header">
          <span className="title">REGISTER</span>
          <span className="toLogin">
            <span>Already have an account ?</span><br/>
            <NavLink to="/teacher/login_pad">LOG IN</NavLink> here
          </span>
        </div>

        <Form onSubmit={this.handleSubmit}
          onKeyDown={(e) => {
            if (e.keyCode == 13) {
              e.preventDefault();
            }
          }}
        >
          <FormItem style={{ marginBottom: 0, minHeight: 50 }}>
            {getFieldDecorator('email', {
              rules: [
                { required: true, message: "Please don't leave this blank!" },
                { validator: this.validateEmail },
              ],
            })(<p><Input placeholder="Email Address" autoComplete="off" /></p>)}
          </FormItem>
          <FormItem style={{ marginBottom: 0, minHeight: 50 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              {getFieldDecorator('emailCode', {
                rules: [
                  { required: true, message: "Please don't leave this blank!" },
                ],
              })(<Input style={{ flex: 1 }} placeholder="Email Verification code" autoComplete="off" />)}
              <Button
                style={{ width: 100, marginLeft: 20 }}
                type="primary"
                disabled={emailValidCodeFlag}
                onClick={this.getEmailValidCode}
              >{seconds}</Button>
            </div>
          </FormItem>
          <FormItem style={{ marginBottom: 0, minHeight: 50 }}>
            <Popover content={content} placement="left" trigger="click">
              {getFieldDecorator('password', {
                rules: [
                  { required: true, message: "Please don't leave this blank!" },
                  {
                    pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,30}$/,
                    message: '6-30 bits combination of' +
                      ' letters and numbers',
                  },
                ],
              })(<p><Input type="password" placeholder="Password" autoComplete="off" /></p>)}
            </Popover>
          </FormItem>
          <FormItem style={{ marginBottom: 0, minHeight: 50 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              {getFieldDecorator('imageCode', {
                rules: [
                  { required: true, message: "Please don't leave this blank!" },
                ],
              })(<p style={{ flex: 1 , marginRight: 20 }}><Input placeholder="Verification code" autoComplete="off" /></p>)}
              <div style={{ width: 100, height: 32 }} onClick={this.getTeaRegValidCode}>
                <img style={{ width: 100, height: 32, cursor: 'pointer', float: 'left' }} src={validCodeImg} alt="" />
              </div>
            </div>
          </FormItem>
          <FormItem style={{ marginBottom: 0, minHeight: 56 }}>
            <Checkbox onChange={this.agreeTerms}
              style={{
                width: 340, fontSize: 10, left: 0, bottom: 0, lineHeight: '24px',
              }}
            >By clicking REGISTER, you agree that you read our <NavLink style={{ display: 'block', textIndent: '20px' }} to="/teacher/agreement_pad">TEACHER POLICY</NavLink>
            </Checkbox>
          </FormItem>
          <Button type="primary" className="registry-btn" htmlType="submit">REGISTER</Button>
        </Form>
      </div>
    );
  }
}

const WrapTeacherRegistry = Form.create()(TeacherRegistry);
export default WrapTeacherRegistry
